class BuildOrderService
  include Serviceable
  include StatusObject

  def initialize(cart, customer, params)
    @cart ||= cart
    @customer ||= customer
    @params ||= params
  end

  def call
    ActiveRecord::Base.transaction do
      @store_order = @customer.orders.create!(@params.merge(amount: @cart.amount))
      cart_items_to_order_items(@store_order)
    end
    Status.new(success: true, message: '提交订单成功', obj: @store_order)
  rescue => e
    Status.new(success: false, message: "订单提交失败!订单的出错是#{e.message}", obj: nil)
  end

  private
  def cart_items_to_order_items(order)
    @store_order ||= order
    @cart_items = @cart.items.showable
    @cart_items.each do |item|
      item.itemable_type = "StoreOrder"
      item.itemable_id = @store_order.id
      item.save!
    end
  end
end
